package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.FrameLayout
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.ui.view.PlayerGestureDetectorHelper

/**
 * 手势操作管理布局，具体实现在[ExoPlayerGestureDetectorHelper]
 */
open class ExoPlayerGestureDetectorLayout : FrameLayout, IExoPlayerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private var gestureDetector: PlayerGestureDetectorHelper? = null

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        //判断是否支持手势
        val gesture = gestureDetector?.onTouchEvent(event) ?: false
        if (!gesture) {
            return super.onTouchEvent(event)
        }
        return gesture
    }

    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        if (gestureDetector == null) {
            gestureDetector = config.playerGestureDetectorHelper.invoke(this)
            config.gestureEnable.observeForever(::onGestureEnableCall)
        }
    }

    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        config.gestureEnable.removeObserver(::onGestureEnableCall)
        gestureDetector = null
    }

    /**
     * 是否允许手势操作回调
     */
    private fun onGestureEnableCall(b: Boolean?) {
        gestureDetector?.enableGesture = b ?: false
    }
}